﻿using Framework;
using UnityEngine;
using UnityEngine.InputSystem;

namespace Game
{
    public class SceneControlComponent : TouchComponent, ISceneComponent
    {
        private ScenePetEntity _controlScenePet;
        private int _touchId = -1;

        public SceneControlComponent()
        {
            TouchSystem.Instance.AddTouchComponent(this);
        }
        
        public override void Dispose()
        {
            TouchSystem.Instance.RemoveTouchComponent(this);
            base.Dispose();
        }

        public void SetControlEntity(ScenePetEntity scenePet)
        {
            _controlScenePet = scenePet;
        }
        
        public void Update(float deltaTime)
        {
        }

        protected override void OnTouchBegan(GameTouch touch)
        {
            if (_touchId > -1)
            {
                return;
            }
            _touchId = touch.touchId;
            base.OnTouchBegan(touch);
            OnPress(touch);
        }

        protected override void OnTouchMoved(GameTouch touch)
        {
            if (_touchId != touch.touchId)
            {
                return;
            }
            base.OnTouchMoved(touch);
            OnPress(touch);
        }

        protected override void OnTouchEnded(GameTouch touch)
        {
            if (_touchId != touch.touchId)
            {
                return;
            }
            base.OnTouchEnded(touch);
            _controlScenePet.GetComponent<ScenePetBehaviorComponent>()?.PressRelease();
            _touchId = -1;
        }

        private void OnPress(GameTouch touch)
        {
            float halfScreenWidth = Screen.width * 0.5f;
            if (touch.screenPosition.x < halfScreenWidth)
            {
                _controlScenePet.GetComponent<ScenePetBehaviorComponent>()?.PressLeft();
            }
            else
            {
                _controlScenePet.GetComponent<ScenePetBehaviorComponent>()?.PressRight();
            }
        }
    }
}